package uk.ac.salfordcc.sccmobile;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sccmobile.helper.AlertDialogManager;
import sccmobile.helper.ConnectionDetector;
import sccmobile.helper.JSONParser;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
 

public class MyStudents extends ListActivity {
	
	Intent intent = getIntent();

	String username, password;
	
    // Connection detector
    ConnectionDetector cd;
 
    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();
 
    // Progress Dialog
    private ProgressDialog pDialog;
 
    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();
 
    ArrayList<HashMap<String, String>> myStudentsList;
    ArrayList<HashMap<String, String>> tracksList;
    
    // albums JSONArray
    JSONArray albums = null;
 
    // albums JSON url
//    private static final String URL_ALBUMS = "http://api.androidhive.info/songs/albums.php";
    private static final String URL = "http://si.salfordcc.ac.uk/ws/srv_myStudents-android.php";
    
    // ALL JSON node names
    private static final String TAG_ID = "s_studentReference";
    private static final String STUDENT_NAME = "name";
    private static final String TAG_SONGS_COUNT = "songs_count";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
		// Show the Up button in the action bar.
		setupActionBar();
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_students);
		
    	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		String storedUsername = sp.getString("USERNAME", ""); //returns "" if not stored.
		username = storedUsername;
		password = sp.getString("PASSWORD", "");
		
		Log.e("MY StudentS...STORED USERNAME: ",storedUsername);		
		
        cd = new ConnectionDetector(getApplicationContext());
 
        // Check for internet connection
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(MyStudents.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }
 
        // Hashmap for ListView
        myStudentsList = new ArrayList<HashMap<String, String>>();
 
        // Loading Albums JSON in Background Thread
        new LoadAlbums().execute();
 
        // get listview
        ListView lv = getListView();
 
        /**
         * Listview item click listener
         * TrackListActivity will be lauched by passing album id
         * */
        lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                    long arg3) {
                // on selecting a single album
                // TrackListActivity will be launched to show tracks inside the album
                //Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
 
                // send album id to tracklist activity to get list of songs under that album
                //String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
                //i.putExtra("album_id", album_id);               
 
                //startActivity(i);
            }
        });
    }
 
    /**
     * Background Async Task to Load all Albums by making http request
     * */
    class LoadAlbums extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MyStudents.this);
            pDialog.setMessage("getting students ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        /**
         * getting Albums JSON
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
 
            // getting JSON string from URL
            //String json = jsonParser.makeHttpRequest(URL, "GET", params);
            String json = jsonParser.makeHttpRequest(URL, "GET", params, username, password);
            
            // Check your log cat for JSON reponse
            //Log.d("Albums JSON: ", "> " + json);
 
            Log.v("THIS IS THE JSON", json);
            
            if (json == "")
            {
            	
            }
            else
            {
                
						            try {
						            	Log.e("message","in the try");
						                JSONObject jObj = new JSONObject(json);
						                if (jObj != null) {
						                	Log.e("message","in the if");
						                	//String album_id = jObj.getString(TAG_ID);
						                    //String album_name = jObj.getString("students");
						                    albums = jObj.getJSONArray("students");
						 
						                    //Log.d("students JSON: ", "> " + json);
						                    
						                    
						                    
						                    
						                    
						                	Log.e("message","last line before if");                    
						                    if (albums != null) {
						                    	Log.e("message","in the albums");
						                    	
						                    	Log.e("studnets count","..."+albums.length());
						                    	
						                    	
						                    	
						                        // looping through All songs
						                        for (int i = 0; i < albums.length(); i++) {
						                            JSONObject c = albums.getJSONObject(i);
						 
						                            
						                            Log.e("marker","...............");
						                            
						                            //Log.d("student","..>"+c);
						                            
						                            
						                            // Storing each json item in variable
						
						                            String name = c.getString("name");
						                            String s_studentreference = c.getString("s_studentreference");
						                            
						                            
						                            
						                            Double att3wk = c.getDouble("att3wk");
						                            
						                            int int_att3wk = (int) Math.round(att3wk);
						                            
						                            
						                            Log.d("variables",Integer.toString(int_att3wk));
						                            
						                            
						                            
						                            Log.d("variables","name: "+name);
						                            Log.d("variables","name: "+s_studentreference);
						
						                            
						                            // creating new HashMap
						                            HashMap<String, String> map = new HashMap<String, String>();
						 
						                            // adding each child node to HashMap key => value
						                            map.put("s_studentReference", s_studentreference);
						                            map.put("name", name);
						                            map.put("att3wk", Integer.toString(int_att3wk));
						                            
						                            Log.e("marker","........end ......");
						                            
						                            //map.put(TAG_DURATION, duration);
						 
						                            // adding HashList to ArrayList
						                            myStudentsList.add(map);
						                            
						                            Log.e("marker","........end for......");
						                        }
						                    } else {
						                        Log.d("Albums: ", "null");
						                    }
						                }            	
						
						            } catch (JSONException e) {
						                e.printStackTrace();
						            }
            	
            }
            
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        

        
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all albums
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                	
                	
                	//String[] values, positions
                	
                    ListAdapter adapter = new SimpleAdapter(
                            MyStudents.this, 
                            myStudentsList,
                            R.layout.list_item_students, 
                            new String[] { TAG_ID,
                                    STUDENT_NAME, TAG_SONGS_COUNT, "s_studentReference","att3wk" }, new int[] {
                                    R.id.album_id, R.id.album_name, R.id.s_studentReference, R.id.s_studentReference , R.id.att3wk});
/*
                     ListAdapter adapter = new SimpleAdapter(
                            students.this, 
                            albumsList,
                            R.layout.list_item_students, 
                            new String[] { TAG_ID,
                                    TAG_NAME, TAG_SONGS_COUNT, "s_studentReference" }, new int[] {
                                    R.id.album_id, R.id.album_name, R.id.s_studentReference, R.id.songs_count });
 
 */ 
                    // updating listview
                    setListAdapter(adapter);
                }
            });
 
        }
 
    }
	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.display_message, menu);
		return true;
	}
    
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
    
    
}